<template>
  <div v-if="isShow" :id="echartId"  shallowRef="Echarts" :key="echartKey"
  style="overflow: hidden;height: 100%;"
  :style="`min-height:${isInCard?'120':echartHeight}px`"
  ></div>
  <el-scrollbar v-else><el-empty :description="emptyDes" :image-size="100" :image="emptyImage"/></el-scrollbar>
</template>
<script>
import { defineComponent, toRefs, reactive, onMounted,ref,watch,onUnmounted,onActivated } from 'vue'
import * as echarts from 'echarts'
import { toThousands } from '@/utils/number-util'
export default defineComponent({
  name: 'LineEchat',
  props: {
    echartData: Object,
    echartId:String,
    echartHeight: {
        type: Number,
        required: false,
        default: 300
    },
    emptyImage: { // 无数据时的图片
        type: String,
        required: false,
        default: ''
    },
    emptyDes: { // 无数据时的文案
        type: String,
        required: false,
        default: '暂无数据'
    },
    rightDownExplain: { // 右下角文案
        type: String,
        required: false,
        default: ''
    },
    isInCard: { //  是否在卡片中显示
        type: Boolean,
        required: false,
        default: false
    },
    smooth: { //  是否平滑曲线
        type: Boolean,
        required: false,
        default: false
    },
    showSymbol: { //  是否显示线上的点
        type: Boolean,
        required: false,
        default: true
    },
    isShowAreaStyle: { //  是否显示面积
        type: Boolean,
        required: false,
        default: false
    },
    ShowAreaStyleLine: { // 显示line面积的index list [0,1]，默认第一条线显示面积
        type: Array,
        required: false,
        default: () => { return [0] }
    },
    areaStyleColor: { // line面积线的渐变颜色
        type: Array,
        required: false,
        default: () => { return [{start: 'rgba(255,71,10, 0.20)', end: 'rgba(255,255,255, 0)'}] }
    },
    tooltipBg: { // 悬浮提示信息背景色
        type: String,
        required: false,
        default: '#ffffff'
    },
    tooltipBorderColor: {
        type: String,
        required: false,
        default: ''
    },
    tooltipTxtColor: { // 悬浮提示信息文字颜色
        type: String,
        required: false,
        default: '#333333'
    },
    legendLeft: { // 图例位置
        type: String,
        required: false,
        default: '0'
    },
    legendBottom: { // 图例位置 下边距
        type: String,
        required: false,
        default: '0'
    },
    legendTxtColor: { // 图例文字颜色
        type: String,
        required: false,
        default: '#666666'
    },
    xAxisLineColor: { // x轴 线的颜色
        type: String,
        required: false,
        default: '#cfd1d3'
    },
    xAxisLabelColor: { // x轴 文字颜色
        type: String,
        required: false,
        default: '#333333'
    },
    xAxisLabelInterval: { // x轴 label 隐藏规则
        type: Number,
        required: false,
        default: 0 // 默认强制都显示 1为间隔1个显示 2为间隔2个显示 依次类推
    },
    xAxisLabelRotate: { // x轴 文字旋转角度
        type: String,
        required: false,
        default: '0'
    },
    yAxisLabelColor: { // y轴 文字颜色
        type: String,
        required: false,
        default: '#999999'
    },
    ySplitLineColor: { // 背景线条 颜色
        type: String,
        required: false,
        default: '#EAEBEB'
    },
    isShowYLabelUnit: { //  是否显示y周数值后面的单位
        type: Boolean,
        required: false,
        default: false
    },
    tooltipFormatter: { //  是否显示y周数值后面的单位
        type: Function,
        required: false
    },
  },
  setup(props) {
    let echartKey = ref(Date.now())
    let isShow = ref(true)
    let seriesData = ref([])
    const state = reactive({
      option: {}
    })
    const renderEchartBar = () => {
      state.option = {
        tooltip: {
          trigger: 'axis',
          confine: true,
          padding:10,
          backgroundColor: props.tooltipBg,
          borderColor: props.tooltipBorderColor,
          textStyle:{
            color: props.tooltipTxtColor,
          },
          formatter: props.tooltipFormatter || null,
          valueFormatter: function (value) {
            let unit = props.echartData.yData[0].unit?props.echartData.yData[0].unit: '';
            return value ? (value + unit) : "-";
          }
        },
        color: ['#FF5353','#477AFD','#C09F88','#48372A'],
        legend: {
          // data: props.echartData.xLable
          left: props.legendLeft, // 或者使用像素值，例如 '50px'
          bottom:  props.legendBottom,
          itemHeight: 8,
          itemWidth: 15,
          textStyle: {
            color: props.legendTxtColor
          }
        },
        // 添加备注
        graphic: {
            type: 'text',
            right: 20,
            bottom: 5,
            style: {
                text: props.rightDownExplain,
                fill: '#999999',
                fontSize: props.isInCard?12:14
                // 其他样式...
            }
        },
        grid: {
          //以div为中心 向右缩进30%
          left: "2%",
          right: "0%",
          top: "10%",
          bottom: "20%",
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: props.echartData.xData,
            axisLine: {
              lineStyle: {
                color:props.xAxisLineColor, // 坐标刻度线
                width:'1'
              },
            },
            axisLabel:{
              interval: 0,  // 强制让所有的字段展示
              rotate: props.xAxisLabelRotate,   // 将字段旋转30度
              textStyle:{
                color: props.xAxisLabelColor // 标签文字
              }
            },
            axisTick: {		//Y轴刻度线
              show:false,
              // inside: true, // 是否在内侧展示
              alignWithLabel: true,
            }
          },
        ],
        yAxis:  [
            {
              type: 'value',
              splitNumber:6,
              // minInterval: 1, // y轴刻度间隔
              axisLabel:{
                show: true, //隐藏y轴
                formatter: (e) => {
                  let unit = props.echartData.yData[0].unit?props.echartData.yData[0].unit: ''
                  return props.isShowYLabelUnit ? e + unit : e
                },
                textStyle:{
                  color: props.yAxisLabelColor
                }
              },
              splitLine: {
                // show: props.echartData.xData.length > 7  ? true : false,
                length: 3,
                lineStyle:{
                  type:'dashed', //背景线条设置
                  color: props.ySplitLineColor
                }
              },
              axisLine: {
                lineStyle: {
                  color: '#EAEBEB',
                },
              },
              axisTick: {		//Y轴刻度线
                show:false,
                alignWithLabel: true,
              },
            },
            {
              type: 'value',
              // min: 0,
              // max: 200,
              // interval: 50,
              splitNumber:6,
              axisLabel: {
                show: false, //隐藏y轴
              },
              splitLine: {
                show:false,
                lineStyle:{
                  type:'dashed', //背景线条设置
                  color:"#EAEBEB"
                }
              },
            }
        ],
        series: seriesData.value,
      }
    }
    const initeCharts = () => {
      let myChart = echarts.init(document.getElementById(props.echartId))
      // 绘制图表
      myChart.clear()
      myChart.setOption(state.option,true)
      window.addEventListener("resize", () => {
        if(myChart != null && myChart.resize != null){
          setTimeout(()=>{
            myChart.resize()
          })
        }
      },true)
    }
    const packageSeriesData = () => {
      seriesData.value = []
      if(props.echartData.yData && props.echartData.yData.length > 0){
        let showNum = 0
        let isShowYAxis = true
        props.echartData.yData.forEach(function (item,yIndex) {
            showNum = showNum + 1
            if(showNum > 1){
              if((item.unit && props.echartData.yData[0].unit) && (item.unit == props.echartData.yData[0].unit)){
                isShowYAxis = false
              } else if(!item.unit  && !props.echartData.yData[0].unit ){
                isShowYAxis = false
              }
            }
            console.log('isShowYAxis' + isShowYAxis)
            let series = {
              name: item.name,
              data: item.data,
              type: 'line',
              yAxisIndex:item.isShow && (showNum>1 && isShowYAxis)? 1: 0,
              showBackground: false,
              smooth: props.smooth,
              showSymbol: props.showSymbol,
              symbolSize:4,
              areaStyle: {
                normal: {
                  opacity: props.ShowAreaStyleLine.indexOf(yIndex) > -1 && props.isShowAreaStyle ? 1: 0,
                  color: {
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: props.isShowAreaStyle && props.ShowAreaStyleLine.indexOf(yIndex) > -1 ? props.areaStyleColor[yIndex].start : '#ffffff', // 0% 处的颜色
                      },
                      {
                        offset: 1,
                        color: props.isShowAreaStyle && props.ShowAreaStyleLine.indexOf(yIndex) > -1 ? props.areaStyleColor[yIndex].end : '#ffffff', // 100% 处的颜色
                      }
                    ],
                    globalCoord: false, // 缺省为 false
                  },
                },
               },
              itemStyle: {
                normal: {
                  // color: item.type == 'line'?'#FF690A':'', //改变折线点的颜色
                  lineStyle: {
                    // color: item.type == 'line'?'#FF690A':'' ,//改变折线颜色
                    width:1
                  },
                  //这里设置柱形图圆角 [左上角，右上角，右下角，左下角]
            
                  label: {
                    // show: item.isShow && item.type == 'bar' && item.data.length < 8 ? true : false, //开启数值显示显示
                    show:false,
                    position: 'top', //在上方显示
                    formatter:function (params){
                      // console.log(params)
                      if(params.value && params.value >0){
                        return toThousands(params.value) + (item.unit?item.unit:'')
                      } else {
                        return ""
                      }
                    },
                    textStyle: { //数值样式
                      color: '#C09F88',
                      fontSize: 14
                    }
                  }
                }
              },
              backgroundStyle: {
                color: 'rgba(255, 255, 255, 0.1)',
              }
            }
            seriesData.value.push(series)
        })
        renderEchartBar()

      }
    }
    onMounted(() => {
    })
    onUnmounted(() => {
      // myChart ?myChart.dispose():'' // （在图表容器被销毁之后，调用 echartsInstance.dispose 销毁实例）
    })
    onActivated(() => {
      // myChart.resize()
      console.log('onActivated')
      let myEchart = document.getElementById(props.echartId)
      if(myEchart){
        myEchart.removeAttribute('_echarts_instance_');
        setTimeout(() => {
                initeCharts()
              }, 200)
      }
    })
    watch(
        ()=>props.echartData,
        (val,preVal)=>{
          //val为修改后的值,preVal为修改前的值
          console.log("message",val,preVal)
          if(!val.yData || val.yData.length < 1) {
            isShow.value = false
          }else {
            isShow.value = true
            packageSeriesData()
            setTimeout(() => {
              initeCharts()
            }, 200)
            echartKey.value++
          }
        },
        {
          //如果加了这个参数，值为true的话，就消除了惰性，watch会在创建后立即执行一次
          //那么首次执行，val为默认值,preVal为undefined
          immediate:true,
          //这个参数代表监听对象时，可以监听深度嵌套的对象属性
          //比如message是一个对象的话，可以监听到message.a.b.c，也就是message下的所有属性
          deep:true,
        }
    )
    return {
      isShow,seriesData,...toRefs(state),echartKey
    }
  },
})
</script>

<style lang="scss" scoped>

</style>
